<?php
class UnzipPlugin extends Action implements IUploader {
	private $last_error = '';
	private $fs = false;
	/* (non-PHPdoc)
	 * @see Action::execute()
	 */
	public function execute($params) {
		$I = check_login ( ADMIN_LOGIN_PAGE );
		rqrestore ( 'UnzipPlugin', false );
		$tmpdir = TMP_PATH . 'plupload';
		$count = irqst ( 'uploader_count', 0 );
		$data = array ('success' => true );
		if ($count > 0) {
			$this->fs = getFileSystem ();
			if (! $this->fs) {
				need_transit ( "filesmgr", $this->url, 'UnzipPlugin' );
			}
			rqdel('UnzipPlugin');
			@set_time_limit ( 0 );
			$uploader = $this; //得到文件上传器
			$efs = array ();
			for($i = 0; $i < $count; $i ++) {
				$tmpfile = new UploadTmpFile ( $i, $tmpdir );
				$rst = false;
				if ($tmpfile->isuploaded () && $uploader->allowed ( $tmpfile->file_ext )) {
					$rst = $uploader->save ( $tmpfile );
				} else {
					elog ( "文件上传失败: 文件上传不完整或文件类型不允许。" );
				}
				if ($rst === false) {
					elog ( "文件上传失败: " . $uploader->get_last_error () );
					$efs [] = $tmpfile->name;
				}
				$tmpfile->delete();
			}
			if (! empty ( $efs )) {
				$cnt = count ( $efs );
				$data ['msg'] = "本次共有{$cnt}个文件未能正确上传：\n" . implode ( "\n", $efs );
			}
		}
		return new JsonView ( $data );
	}
	/**
	 * 保存
	 * @see IUploader::save()
	 */
	public function save($file) {
		$_fs = $this->fs;
		if ($_fs) {
			$tmpdir = TMP_PATH . $file->basename;
			if (! is_dir ( $tmpdir ) && ! mkdir ( $tmpdir )) {
				return false;
			}
			$tmp_file = $file->tmpname;
			$zf = new ZipArchive ();
			if ($zf->open ( $tmp_file )) {
				$zf->extractTo ( $tmpdir );
				$zf->close ();
				$this->moveFiles ( $_fs, $tmpdir, $tmpdir );
			}
			rmdirs ( $tmpdir );
			return true;
		} else {
			return false;
		}
	}
	/*
	 * (non-PHPdoc) @see IUploader::get_last_error()
	 */
	public function get_last_error() {
		return $this->last_error;
	}
	/*
	 * (non-PHPdoc) @see IUploader::getMaxSize()
	 */
	public function getMaxSize() {
		return 20971520000; // 20M
	}
	/*
	 * (non-PHPdoc) @see IUploader::getTypes()
	 */
	public function allowed($ext) {
		static $types = false;
		if (! $types) {
			$types = array ('.zip' );
		}
		return in_array ( $ext, $types );
	}
	private function moveFiles($fs, $dir, $tmpdir) {
		$hd = opendir ( $dir );
		if ($hd) {
			$srcdir = trim ( str_replace ( array (APP_PATH, DS ), array ('', '/' ), $dir ), '/' );
			$destdir = trim ( str_replace ( array ($tmpdir, DS ), array ('', '/' ), $dir ), '/' );
			while ( ($f = readdir ( $hd )) !== false ) {
				if ($f == '.' || $f == '..') {
					continue;
				}
				$fs->chdir ( '/' );
				if (is_dir ( $dir . '/' . $f )) {
					$fs->mkdir ( $destdir . '/' . thefilename ( $f ) );
					$this->moveFiles ( $fs, $dir . '/' . $f, $tmpdir );
				} else {
					$f = thefilename ( $f );
					$fs->move ( $srcdir . '/' . $f, $destdir . '/' . $f );
				}
			}
			closedir ( $hd );
		}
	}
}